package final2107.day05;

public class BinarySearch {
    public static void main(String[] args) {
        //二分查找算法
        int[] ary = {2,4,6,8,12,15,23,56,67,89};
        int target = 561;
//        int index = getIndex(ary,target);
//        System.out.println(index);
    }

    //查找元素的下标
    public static int getIndex(int[] ary,int target){
        //定义start,end,middle变量
        int start = 0,end=ary.length-1,middle;
        while (start<=end){
            middle = start+((end-start)>>1);
            if (target==ary[middle])
                return middle;
            if (target>ary[middle])
                start = middle+1;
            if (target<ary[middle])
                end = middle-1;
        }
        return -1;
    }

    public int getIndexB(String[] ary,String target){
        int start=0,end=ary.length-1,middle;
        while (start<=end){
            middle = start+((end-start)>>1);
            if (target.compareTo(ary[middle])==0)
                return middle;
            if (target.compareTo(ary[middle])>0)
                start = middle+1;
            if (target.compareTo(ary[middle])<0)
                end = middle-1;
        }
        return -1;

    }
}
